#include "./sensor.h"
#include "../device/gpio.h"

namespace driver {

using namespace device::gpio;

using PL = PB<3>;
using CP = PB<4>;
using Q7 = PB<5>;

Sensor::Sensor() {
    RCC->APB2ENR |= RCC_APB2ENR_IOPBEN;

    config_pp_out<PL, CP>();
    config_float_input<Q7>();
}

uint16_t Sensor::read() {
    AUTO_LOCK(m_mutex);

    uint16_t val = 0;
    PL::clr();
    PL::set();

    for (uint8_t i = 0; i < 16; i ++) {
        val <<= 1;
        if (Q7::read()) {
            val ++;
        }
        CP::set();
        CP::clr();
    }
    return val;
}

uint16_t Sensor::status() {
    using namespace utils;
    uint16_t val = read();

    return (is_clr_bit<0>(val) << 0) +
        (is_clr_bit<1>(val) << 1) +
        (is_set_bit<8>(val) << 2) +
        (is_set_bit<9>(val) << 3) +
        (is_set_bit<10>(val) << 4) +
        (is_set_bit<11>(val) << 5) +
        (is_clr_bit<12>(val) << 6) +
        (is_clr_bit<13>(val) << 7) +
        (is_clr_bit<2>(val) << 8)
        ;
}

}
